#include "guiterm.hpp"

CommandHistory::CommandHistory()
{
	historyPos = 0;
	
	HistoryEntry *entry = new HistoryEntry();
	history.push_back(entry);
}

CommandHistory::~CommandHistory()
{
	for(unsigned ii=0; ii<history.size(); ii++)
		delete history[ii];
}

string CommandHistory::up(string typed)
{
	// Can't scroll up past the first entry
	if(historyPos+1 >= (int)history.size())
		return typed;
	
	updateEntry(typed);
	historyPos++;
	return history[historyPos]->currentText;
}

string CommandHistory::down(string typed)
{
	// Can't scroll down past the last entry
	if(historyPos==0)
		return typed;
	
	updateEntry(typed);
	historyPos--;
	return history[historyPos]->currentText;
}

void CommandHistory::updateEntry(const string &typed)
{
	if(strcmp(typed.c_str(), history[historyPos]->currentText))
	{
		if(history[historyPos]->originalText)
			free(history[historyPos]->currentText);
		else
			history[historyPos]->originalText = history[historyPos]->currentText;
		history[historyPos]->currentText = strdup(typed.c_str());
	}
}

void CommandHistory::commit(string typed)
{
	if(history[historyPos]->originalText)
	{
		free(history[historyPos]->currentText);
		history[historyPos]->currentText = history[historyPos]->originalText;
		history[historyPos]->originalText = NULL;
	}
	
	if(history[0]->originalText) {
		free(history[0]->originalText);
		history[0]->originalText = NULL;
	}
	if(history[0]->currentText) {
		free(history[0]->currentText);
	}
	history[0]->currentText = strdup(typed.c_str());
	
	HistoryEntry *newEntry = new HistoryEntry();
	history.push_front(newEntry);
	
	// TODO: Expire old entries
	
	historyPos = 0;
}

CommandHistory::HistoryEntry::HistoryEntry()
{
	currentText = strdup("");
	originalText = NULL;
}

CommandHistory::HistoryEntry::~HistoryEntry()
{
	if(currentText)
		free(currentText);
	if(originalText)
		free(originalText);
}


